package com.example.recyclerviewdemo.diffdemo

import android.os.Bundle
import androidx.recyclerview.widget.DiffUtil
import com.example.recyclerviewdemo.model.bean.ChatBean


class DiffUtilCallback(private val oldList: MutableList<ChatBean>,
                       private val newList: MutableList<ChatBean>): DiffUtil.Callback() {

    override fun getOldListSize(): Int {
        return oldList.size
    }

    override fun getNewListSize(): Int {
        return newList.size
    }

    //比较id id相同了才比较内容
    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
         return oldList[oldItemPosition].id == newList[newItemPosition].id
    }

    /*
     * 比较内容
     * 只需要比较当前界面上显示的元素
     * */
    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        val old = oldList[oldItemPosition]
        val new = newList[newItemPosition]

        //在聊天列表里 contentText 是高频修改的内容
        return (old.titleText == new.titleText) && (old.contentText == new.contentText) && (old.time == new.time)
    }

    override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
        val old = oldList[oldItemPosition]
        val new = newList[newItemPosition]

        val payload = Bundle()
        //有修改，放到Bundle
        if (old.titleText != new.titleText) {
            payload.putString("titleText", new.titleText)
        }
        if (old.contentText != new.contentText) {
            payload.putString("contentText", new.contentText)
        }
        if (old.time != new.time) {
            payload.putLong("time", new.time)
        }
        return if (payload.size() == 0) null else payload
    }
}